package service

import (
	"context"
	"github.com/aberic/gnomon"
	"github.com/aberic/gnomon/log"
	"google.golang.org/grpc"
	proto "gykjgit.dccnet.com.cn/chain/proto/swarm"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"time"
)

var (
	scheduled *time.Timer // 超时检查对象
	delay     = time.Second * time.Duration(5)
	stop      chan struct{} // 释放当前角色chan
)

func init() {
	scheduled = time.NewTimer(delay)
	stop = make(chan struct{}, 1)
}

func ScheduledStartSend() {
	scheduled.Reset(time.Millisecond * time.Duration(5))
	for {
		select {
		case <-scheduled.C:
			if cSync, err := client.Obtain().Resource().StatsAll4Containers(context.Background()); nil != err {
				log.Error("send stats all", log.Err(err))
			} else {
				log.Debug("send", log.Field("cSync", cSync))
				if _, err := gnomon.GRPCRequestSingleConn("swarm:20219", func(conn *grpc.ClientConn) (i interface{}, err error) {
					// 创建grpc客户端
					cli := proto.NewResourceServerClient(conn)
					// 客户端向grpc服务端发起请求
					return cli.ContainersSync(context.Background(), cSync)
				}); nil != err {
					log.Error("send sync", log.Err(err))
				}
			}
			scheduled.Reset(delay)
		case <-stop:
			return
		}
	}
}
